
from ctypes import *
from uart.dll_api import HLUART_DLL
from uart.dll_api import Element_Struct
from uart.dll_api import data_type_dic
#实例化dll
HLUART=HLUART_DLL()    
    
class Element():
    '''
    e_type:类型,data:32位值,val():实际值
    '''
    e_type:type
    data:c_uint32

    def __init__(self,e_type:type=c_int32,val=0,element_struct:Element_Struct=None) -> None:
        if(element_struct!=None):
            self.e_type=data_type_dic[element_struct.type]
            self.data=element_struct.data
        else:
            self.e_type=e_type
            self.val(val)
    
    def val(self,val=None):
         if(val!=None):
            self.data=HLUART.data(self.e_type(val))
         return HLUART.val(self.data,self.e_type)
     
    def __repr__(self) -> str:
        return str(self.val())
def get_bytes(*elements)->bytes:
    
    res=bytes()
    for c in get_buffer(*elements):
        c:c_uint8
        res+=bytes([c])
    return res
def get_buffer(*elements)->Array[c_uint8]:
    '''
    通过elements获得buffer
    '''
    length=len(elements)
    size=0
    elements_struct=(Element_Struct*length)()
    for i in range(length):
        e:Element=elements[i]
        elements_struct[i].type=HLUART.type_data_dict[e.e_type]
        elements_struct[i].size=HLUART.type_get_size(elements_struct[i].type)
        elements_struct[i].data=e.data
        size+=elements_struct[i].size+1
    buffer=(c_uint8*size)()
    HLUART.write_buffer(buffer,length,elements_struct)
    return buffer    

def get_elements(buffer:Array[c_uint8]=None,buffer_bytes:bytes=None)->list[Element]:
    '''
    通过buffer得到elements
    '''
    if(buffer==None):
        buffer=(c_uint8*len(buffer_bytes))()
        for i in range(len(buffer_bytes)):
            buffer[i]=buffer_bytes[i]
    length=HLUART.get_elements_length(buffer)
    elements=[]
    elements_struct=(Element_Struct*length)()
    HLUART.read_buffer(buffer,length,elements_struct)
    for e_s in elements_struct:
        elements.append(Element(element_struct=e_s))
    return elements
# res=get_bytes(Element(c_float,3.1))

# print( get_elements(buffer_bytes=res))
#aaaa